<template>
  <div class="panel" v-loading="loading">
    <div class="panel-header cleanMB">{{ title || '统计' }}</div>
    <TableSearch
      ref="tableSearch"
      v-if="echartsInit"
      :tableBtns="tableBtns"
      :formItemsInline="renderItems"
      :form="form"
      :columns="columns"
      :tableData="tableData"
      @handleTableData="handleTableData"
      :pageNameDisplay="false"
      :paginationDisplay="false"
      :rules="rules"
      @reset="handleReset"
    >
      <template v-for="formItem in renderItems">
        <slot :name="formItem.slot" :slot="formItem.slot" />
      </template>
      <template slot="date">
        <el-form-item prop="date">
          <SearchDatePicker
            @change="datePickerChange"
            :start.sync="form.startTime"
            :end.sync="form.endTime"
            :disable-date="diableDate"
            :type="timeUnit"
          />
        </el-form-item>
      </template>
      <template slot="address">
        <el-form-item>
          <HycAddressCascader
            ref="area"
            v-model="form.area"
            :level="addressLevel"
            :clearable="true"
          />
        </el-form-item>
      </template>
      <template slot="merchant" v-if="form.containSubMch">
        <el-form-item>
          <!-- <el-autocomplete
            style="width: 100%"
            placeholder="请输入代理商名称"
            v-model="selectMerchant"
            :fetch-suggestions="handleQueryMerchant"
            @select="handleSelect"
          /> -->
          <SearchMerchants v-model="form.mchUserId" :defaultOptions="false" />
        </el-form-item>
      </template>
      <template slot="station">
        <el-form-item>
          <el-autocomplete
            style="width: 100%"
            placeholder="请输入电站名称"
            v-model="selectStation"
            :fetch-suggestions="handleQueryStation"
            @select="handleSelectStation"
          />
        </el-form-item>
      </template>
      <!-- <template slot="merchantCheckbox" v-if="renderMchSub">
        <el-form-item>
          <el-checkbox v-model="form.containSubMch"
            >本级和下级代理商数据</el-checkbox
          >
        </el-form-item>
      </template> -->
    </TableSearch>
    <!-- <div class="chart-submerchant-export">
      <div>
        <el-switch v-model="showSub" @change="handleShowSub"> </el-switch>
        下级代理商数据
        <el-checkbox v-model="showSub" @change="handleShowSub">
          本级和下级代理数据
        </el-checkbox>
      </div>
    </div> -->
    <div ref="chartContainer" class="chart-container">
      <div class="echart-panel-time_range">
        <el-radio-group
          size="small"
          v-model="range"
          @change="handleRangeChange"
          v-if="rangeButton"
        >
          <el-radio-button
            v-for="item in radioButtons"
            :label="item.value"
            :key="item.value"
            >{{ item.label }}</el-radio-button
          >
        </el-radio-group>
      </div>
      <div ref="mapInstance" style="padding: 0px 24px 20px 36px"></div>
    </div>
  </div>
</template>
<script>
import TableSearch from '@/components/TableSearch'
import HycAddressCascader from '@/components/hycAddressCascader'
import SearchMerchants from '@/components/SearchMerchants'
import * as echarts from 'echarts'
import * as visualizationFun from '@/utils/visualizationFun'
import dayjs from 'dayjs'
import { selectSubMerchant } from '@/api/common'
import { selectStationList } from '@/api/statistics'

export default {
  name: 'EchartPanel',
  components: { TableSearch, HycAddressCascader, SearchMerchants },
  watch: {
    'form.containSubMch': {
      handler(val) {
        if (!val) {
          this.form.mchUserId = ''
          this.selectMerchant = ''
        }
      },
    },
  },
  destroyed() {
    window.removeEventListener('resize', this.resizeChart)
  },
  data() {
    return {
      eventHandler: null,
      selectMerchant: '',
      timeout: null,
      selectStation: '',
      stationTimeout: null,
      range: '',
      tableBtns: [],
      form: {
        containSubMch: true,
        mchUserId: '',
      },
      showSub: false,
      chart: null,
      echartsInit: false,
      constRadioButtons: {
        date: [
          {
            value: 7,
            label: '最近7天',
          },
          {
            value: 30,
            label: '最近30天',
          },
        ],
        month: [
          {
            value: 6,
            label: '最近6月',
          },
          {
            value: 12,
            label: '最近12月',
          },
        ],
      },
      rules: {
        date: [
          {
            validator: (rule, value, callback) => {
              if (
                !this.form.startTime ||
                this.form.startTime === '' ||
                !this.form.endTime ||
                this.form.endTime === ''
              ) {
                switch (this.timeUnit) {
                  case 'date':
                    callback(
                      new Error('必须选择开始和结束时间,最大查询范围为30天')
                    )
                    break
                  case 'month':
                    callback(
                      new Error('必须选择开始和结束时间,最大查询范围为12个月')
                    )
                    break
                  default:
                    break
                }
              } else {
                callback()
              }
            },
          },
        ],
      },
    }
  },
  props: {
    loading: {
      type: Boolean,
      default: false,
    },
    defaultForm: {
      type: Object,
      default: () => {
        return {}
      },
    },
    defaultFormItems: {
      type: [Array, Boolean],
      default: () => ['date', 'address', 'merchant', 'merchantCheckbox'],
    },
    formItemsInline: {
      type: Array,
      default: () => [],
    },
    columns: {
      type: Array,
      default: () => [],
    },
    tableData: {
      type: Object,
      default: () => {
        return {}
      },
    },
    timeUnit: {
      type: String,
      default: 'date',
    },
    addressLevel: {
      type: Number,
      default: 0,
    },
    echartsOption: {
      type: Object,
      default: () => {
        return {}
      },
    },
    rangeButton: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: '统计',
    },
    customReset: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    JSON.stringify(this.echartsOption) !== '{}'
      ? this.initCharts()
      : (this.echartsInit = true)
    this.initForm()
  },
  computed: {
    renderMchSub() {
      return (
        this.$store.getters.userData.type !== 'ADMIN' &&
        this.$store.getters.userData.type !== 'SELF_OPERATION_ADMIN'
      )
    },
    enableMerchant() {
      return !(this.form.area && this.form.area.province)
    },
    renderItems() {
      let frontArr = [
        {
          slot: 'date',
        },
        {
          slot: 'address',
        },
        {
          slot: 'merchant',
        },
        {
          slot: 'station',
        },
      ]
      let endArr = [
        {
          slot: 'merchantCheckbox',
        },
      ]
      frontArr = Array.isArray(this.defaultFormItems)
        ? frontArr.filter((item) => this.defaultFormItems.includes(item.slot))
        : this.defaultFormItems
        ? frontArr
        : []
      endArr = Array.isArray(this.defaultFormItems)
        ? endArr.filter((item) => this.defaultFormItems.includes(item.slot))
        : this.defaultFormItems
        ? endArr
        : []
      return frontArr.concat(this.formItemsInline, endArr)
    },
    radioButtons() {
      return this.constRadioButtons[this.timeUnit]
    },
    diableDate() {
      switch (this.timeUnit) {
        case 'date':
          return { range: 24 * 3600 * 30 * 1000, banTomorrow: true }
        case 'month':
          return {
            range:
              dayjs().subtract(1, 'month').endOf('month').valueOf() -
              dayjs().subtract(12, 'month').startOf('month').valueOf(),
            banTomorrow: true,
          }
        default:
          return ''
      }
    },
  },
  methods: {
    initForm() {
      // 当存在对应的formItem，才会执行这个初始化
      if (
        Array.isArray(this.defaultFormItems) &&
        this.defaultFormItems.includes('date')
      ) {
        if (this.timeUnit === 'date') {
          this.range = 7
          this.form.endTime = dayjs().subtract(1, 'day').endOf('day').valueOf()
          this.form.startTime = dayjs()
            .subtract(this.range, 'day')
            .startOf('day')
            .valueOf()
        }
        if (this.timeUnit === 'month') {
          this.range = 6
          this.form.endTime = dayjs()
            .subtract(1, 'month')
            .endOf('month')
            .valueOf()
          this.form.startTime = dayjs()
            .subtract(6, 'month')
            .startOf('month')
            .valueOf()
        }
      }

      this.form = {
        ...this.form,
        ...this.defaultForm,
      }
    },
    handleReset() {
      if (this.customReset) {
        this.$emit('handleReset', this.form)
      } else {
        this.form = {
          containSubMch: true,
          area: {},
        }
        this.selectStation = ''
        this.initForm()
      }
    },
    handleSelect(val) {
      this.form.mchUserId = val.id
    },
    async handleQueryMerchant(qs, cb) {
      selectSubMerchant({
        userName: qs,
      })
        .then((res) => {
          if (this.timeout) clearTimeout(this.timeout)

          if (!Array.isArray(res)) return

          let list = res.map((item) => {
            return {
              value: item.name,
              id: item.id,
            }
          })
          this.timeout = setTimeout(() => {
            cb(list)
          }, 1000)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleSelectStation(val) {
      this.form.stationIds = [val.id]
    },
    async handleQueryStation(qs, cb) {
      try {
        let res = await selectStationList({
          stationName: qs,
        })
        if (this.stationTimeout) clearTimeout(this.stationTimeout)

        if (!Array.isArray(res)) return
        let list = res.map((item) => {
          return {
            value: item.stationName,
            id: item.id,
          }
        })
        this.stationTimeout = setTimeout(() => {
          cb(list)
        }, 1000)
      } catch (err) {
        console.log(err)
      }
    },
    handleRangeChange(val) {
      if (this.timeUnit === 'date') {
        this.form.endTime = dayjs().subtract(1, 'day').endOf('day').valueOf()
        this.form.startTime = dayjs()
          .subtract(val, 'day')
          .startOf('day')
          .valueOf()
      }
      if (this.timeUnit === 'month') {
        this.form.endTime = dayjs()
          .subtract(1, 'month')
          .endOf('month')
          .valueOf()
        this.form.startTime = dayjs()
          .subtract(val, 'month')
          .startOf('month')
          .valueOf()
      }
      this.$forceUpdate()

      this.handleTableData(this.form)
    },
    handleTableData(params) {
      let validate = true
      if (this.$refs.tableSearch) {
        validate = this.$refs.tableSearch.formValidate()
      }
      if (!validate) return
      let tempParams = { ...params }
      tempParams.area && tempParams.area.province
        ? (tempParams.province = tempParams.area.province)
        : null
      tempParams.area && delete tempParams.area
      this.$emit('handleTableData', tempParams, this.chart)
    },
    datePickerChange() {
      this.range = undefined
    },
    initCharts() {
      this.chart = echarts.init(this.$refs.mapInstance)
      this.chart.setOption(this.echartsOption)

      // window.onresize = () => {
      //   console.log('onresize')
      //   visualizationFun.chartsSizeSet(this.$refs.chartContainer, this.chart)
      // }
      window.addEventListener('resize', this.resizeChart)
      visualizationFun.chartsSizeSet(this.$refs.chartContainer, this.chart)

      this.echartsInit = true
    },
    resizeChart() {
      visualizationFun.chartsSizeSet(this.$refs.chartContainer, this.chart)
    },
  },
}
</script>
<style lang="scss">
.chart-submerchant-export {
  padding: 0 24px 20px 36px;
}

.echart-panel-time_range {
  position: absolute;
  top: 20px;
  left: 50px;
  z-index: 999;
}
.chart-container {
  width: 100%;
  height: 450px;
  position: relative;
}

.cleanMB {
  margin-bottom: 0 !important;
}
</style>
